package com.doudanhua.basecode.rabbitmq;

import com.doudanhua.basecode.dto.DogDto;
import com.doudanhua.basecode.jackson.JsonConvert;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

/**
 * @Author zhangqian
 * @Description 参考：https://docs.spring.io/spring-amqp/docs/2.3.16/api/
 * @Date 2022/11/8 17:08
 */
@Component
@Slf4j
public class MqReceive {

//    /**
//     * 通过指定containerFactory 可以设置接收对象的消息转化器器，比如jackson ，则消费者收到的消息可以是具体的对象
//     *
//     * @param dto
//     * @throws UnsupportedEncodingException
//     */
//    @RabbitHandler
//    @RabbitListener(queues = RabbitMqConfig.QUEUE_BASECODE, containerFactory = "rabbitListenerContainerFactory")
//    public void baseCodeReceive(DogDto dto) throws UnsupportedEncodingException {
//        String charsetName = "UTF-8";
//        //body = new String(message.getBody(), charsetName)
//        //String body = new String(message, charsetName);
//        log.info("mq receive:" + JsonConvert.toJson(dto));
//    }

    @RabbitHandler
    @RabbitListener(queues = RabbitMqConfig.QUEUE_BASECODE)
    public void baseCodeReceive(Message message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) throws IOException {
        try {
            log.info("receive:"+ LocalDateTime.now());
            String charsetName = "UTF-8";
            String body = new String(message.getBody(), charsetName);
            final String receivedExchange = message.getMessageProperties().getReceivedExchange();
            final String receivedRoutingKey = message.getMessageProperties().getReceivedRoutingKey();
            //一个队列绑定到多个exchange时，可以通过 receivedExchange，receivedRoutingKey 定位到具体对应的key 来处理不用的消息
            //String body = new String(message, charsetName);
            log.info("mq receive:" + body);
            //* 无异常就确认消息
            //* basicAck(long deliveryTag, boolean multiple)
            //* deliveryTag:取出来当前消息在队列中的的索引;
            //* multiple:为true的话就是批量确认,如果当前deliveryTag为5,那么就会确认
            //* deliveryTag为5及其以下的消息;一般设置为false

            channel.basicAck(deliveryTag, true);
        } catch (Exception e) {

            channel.basicNack(deliveryTag, false, true);
        }
    }
}
